//
//  ZBTextView.m
//  XZBProduct
//
//  Created by xzb on 2018/8/16.
//  Copyright © 2018年 xzb. All rights reserved.
//

#import "ZBTextView.h"


@interface ZBTextView () <UITextViewDelegate>

@property (nonatomic, assign, getter=isHiddenPlaceholder) BOOL hiddenPlaceholder;

@end

@implementation ZBTextView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _placeholderTextColor = [UIColor grayColor];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(zb_textViewTextchangeEditing) name:UITextViewTextDidChangeNotification object:nil];
    }
    return self;
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)setPlaceholder:(NSString *)placeholder
{
    _placeholder = placeholder;
    [self setNeedsDisplay];
}

- (void)setText:(NSString *)text
{
    [super setText:text];
    [self zb_textViewTextchangeEditing];
}

- (void)setPlaceholderTextColor:(UIColor *)placeColor
{
    _placeholderTextColor = placeColor;
    [self setNeedsDisplay];
}

-(void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    if (!self.isHiddenPlaceholder) {
        
        if (self.attributedPlaceholder) {
            [self.placeholder drawAtPoint:CGPointMake(5, 8) withAttributes:self.attributedPlaceholder];
        } else  {
            UIFont * font = [self font] ? : [UIFont systemFontOfSize:12];
            NSDictionary * dict = @{
                                    NSFontAttributeName : font ,
                                    NSForegroundColorAttributeName : self.placeholderTextColor
                                    };
            [self.placeholder drawAtPoint:CGPointMake(5, 8) withAttributes:dict];
        }
    }
}

-(void)zb_textViewTextchangeEditing
{
    self.hiddenPlaceholder = ![self.text isEqualToString:@""];
    [self setNeedsDisplay];
}

@end
